<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\BaseController;
use App\Http\Requests\Auth\LoginRequest;
use App\Transformers\UserTransformer;
use Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException;

class AuthController extends BaseController
{
    public function login(LoginRequest $request)
    {
        $data = $request->validated();
        $account = array_get($data, 'account');
        $password = array_get($data, 'password');
        if (!$token = \Auth::attempt(['name' => $account, 'password' => $password])) {
            throw new UnauthorizedHttpException('invalid_credentials', '用户明或密码错误');
        }
        return [
            'data' => [
                'token' => $token
            ]
        ];
    }

    public function profile()
    {
        $user = \Auth::user();
        return $this->response->item($user, new UserTransformer());
    }

    public function logout()
    {
        \Auth::logout();
        return $this->response->noContent();
    }
}